import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, Like, Repository } from 'typeorm';
import { Log } from './entities/log.entity';

@Injectable()
export class LogService {
  @InjectRepository(Log)
  private logRepository: Repository<Log>;

  async create(log: Partial<Log>) {
    const newLog = this.logRepository.create(log);
    return await this.logRepository.save(newLog);
  }

  async findAll(
    pageNum: number,
    pageSize: number,
    username?: string,
    path?: string,
    method?: string,
    startTime?: string,
    endTime?: string,
  ) {
    const skipCount = (pageNum - 1) * pageSize;
    const condition: Record<string, any> = {};

    if (username) {
      condition.username = Like(`%${username}%`);
    }
    if (path) {
      condition.path = Like(`%${path}%`);
    }
    if (method) {
      condition.method = method;
    }
    if (startTime && endTime) {
      condition.createTime = Between(new Date(startTime), new Date(endTime));
    }

    const [logs, total] = await this.logRepository.findAndCount({
      where: condition,
      skip: skipCount,
      take: pageSize,
      order: {
        createTime: 'DESC',
      },
    });

    return {
      logs,
      total,
    };
  }
}
